package com.h3c.nem.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.eos.common.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.dto.TbTeacherAllowanceDTO;
import com.h3c.nem.dto.TbTeacherDTO;
import com.h3c.nem.mapper.SdDeptMapper;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbTeacherService;
import com.h3c.nem.service.ITbWorkerService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.ReturnCodeData;
import com.h3c.nem.utils.ReturnDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbTeacherController
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_teacher controller
 * Version: 1.0
 */
@Api(tags = " TbTeacher 接口")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "/tbTeacher",produces = "application/json;charset=utf-8")
public class TbTeacherController {

    @Resource
    private ITbTeacherService tbTeacherService;

    @Resource
    private CommService commService;

    @Resource
    SdDeptMapper sdDeptMapper;

    @Resource
    private ITbWorkerService workerService;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacherDTO", paramType = "query"),
        @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryFuzzyListForPage(@ModelAttribute TbTeacherDTO paramsDTO,
                                                            @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        TbTeacherDTO dto = tbTeacherService.seacherInfo(paramsDTO);
        try {
            //分页
            Page page = PageHelper.startPage(currentPage, pageSize);

            //执行
            List<TbTeacherDTO> resultDTOList = new ArrayList<>();
            if(commService.checkLoginUserOnlyRole(BusiEnumDefine.USER_ROLE_TEACHER)){
                dto.setTeacherId(commService.getLoginUserId());
                resultDTOList = tbTeacherService.selectByDto(dto);
            }else {
                resultDTOList = tbTeacherService.selectFuzzyByDto(dto);
            }
            PageInfo<TbTeacherDTO> pageInfo = page.toPageInfo();
//            PageInfo<TbTeacherDTO> pageInfo = new PageInfo<>(resultDTOList);
            pageInfo.setList(resultDTOList);

            data.put("data",pageInfo);
            data.put("msg", "列表分页模糊查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行列表分页模糊查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: queryListForPage
     * @description: 列表分页精确查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacherDTO", paramType = "query"),
    @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
    @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryListForPage(@ModelAttribute TbTeacherDTO paramsDTO,
                                                       @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //分页
            Page page = PageHelper.startPage(currentPage, pageSize);

            //执行
            List<TbTeacherDTO> resultDTOList = tbTeacherService.selectFuzzyByDto(paramsDTO);
            PageInfo<TbTeacherDTO> pageInfo = page.toPageInfo();
            pageInfo.setList(resultDTOList);
            data.put("data",pageInfo);
            data.put("msg", "列表分页查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacher", paramType = "body")})
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> save(@RequestBody TbTeacherDTO paramsDTO) {
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbTeacherService.insertDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据插入成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行 数据插入 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据修改", notes = "数据修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacher", paramType = "body")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> update(@RequestBody TbTeacherDTO paramsDTO) {
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbTeacherService.updateDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据修改成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据修改 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacher", paramType = "body")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> delete(@RequestBody TbTeacherDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbTeacherService.deleteDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据删除成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行 数据删除 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", "数据删除失败");
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @ApiOperation(value = "导师导出", notes = "导师导出")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbTeacherDTO", paramType = "body")})
    @RequestMapping(value = "/downloadData", method = RequestMethod.POST)
    public Result downloadData(@RequestBody TbTeacherDTO paramsDTO) {
        try {
            TbTeacherDTO dto = tbTeacherService.seacherInfo(paramsDTO);
            File downLoadFile = tbTeacherService.download(dto,"TEACHER_EXPORT","导师导出");
            FileInputStream inputStream = new FileInputStream(downLoadFile);
            byte[] buffer = new byte[(int) downLoadFile.length()];
            inputStream.read(buffer);
            inputStream.close();
            Map<String, String> result = new HashMap<>();
            result.put("file", Base64Utils.encodeToString(buffer));
            result.put("filename", downLoadFile.getName());
            return new Result(true, StatusCodeEnum.NORMAL,result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("导出失败");
        }
    }


    /**
     * @title: importTeacherList
     * @description: 导师导入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @ApiOperation(value = "导师导入", notes = "导师导入")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "导入数据文件", required = true, dataType = "MultipartFile", paramType = "body")})
    @RequestMapping(value = "/importTeacherList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> importTeacherList(@RequestParam(value="file") MultipartFile file) {
        Integer result = tbTeacherService.importTeacherList(file);
        JSONObject data = new JSONObject();
        data.put("data", result);
        data.put("msg", "导师导入");
        data.put("code", ReturnCodeData.SUCCESS);

        log.info("执行 导师导入，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @GetMapping("teacher/{key}")
    public ResponseEntity<JSONObject> teacher(@PathVariable String key){

        return new ReturnDataUtil().success(tbTeacherService.getTeacherByKeyWord(key));
    }

    /**
     * 检查所选员工是否是导师或者是否符合导师认证资质（直接导师认证）
     * @param workerId
     */
    @GetMapping("/checkSelectTeacher")
    public Result checkSelectTeacher(@RequestParam("workerId") String workerId) {
        tbTeacherService.checkSelectTeacher(workerId);
        return new Result(true, StatusCodeEnum.NORMAL);
    }

    /**
     * 判断所选员工是否是导师或者是否符合导师资质（先不导师认证）
     * @param workerId
     * @return
     */
    @GetMapping("/checkWorker")
    public Result checkWorker(@RequestParam("workerId") String workerId){
        String passId = tbTeacherService.checkWorker(workerId);
        return new Result(true, StatusCodeEnum.NORMAL, passId);
    }

    /**
     * @title: syncGrade
     * @description: 同步导师绩效文化惩处信息
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-02-21
     * @version: 1.0
     * @author: j26296
     */
    @ApiOperation(value = "同步绩效等", notes = "同步绩效等")
    @RequestMapping(value = "/syncGrade", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> syncGrade() {
        Integer result = tbTeacherService.syncGrade();
        JSONObject data = new JSONObject();
        data.put("data", result);
        data.put("msg", "同步绩效等相关信息");
        data.put("code", ReturnCodeData.SUCCESS);
        log.info("执行 同步绩效等相关信息，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    /**
     * @title:
     * @description:
     * @createTime: 2022-03-31
     * @version: 1.0
     * @author: j26296
     */
    @ApiOperation(value = "导师不合格邮件", notes = "导师不合格邮件")
    @RequestMapping(value = "/sendEmailByStatus", method = RequestMethod.POST)
    public Result sendEmailByStatus() {
        try {
            tbTeacherService.sendEmailByStatus();
            return new Result(true, StatusCodeEnum.NORMAL, "success");

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(StatusCodeEnum.valueOf(""));
        }
    }

    /**
     * 查询导师津贴
     * 部门名称 转正日期  申报状态 津贴申报日期
     * @param paramsDTO
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("teacherAllowance")
    public Result teacherAllowance(@ModelAttribute TbTeacherAllowanceDTO paramsDTO,
                                   @RequestParam(name = "currentPage") Integer currentPage,
                                   @RequestParam(name = "pageSize") Integer pageSize){
        PageInfo<TbTeacherAllowanceDTO> res = tbTeacherService.getTeacherAllowance(paramsDTO, currentPage, pageSize);
        return new Result(true, StatusCodeEnum.NORMAL, res);
    }

    /**
     * 导师津贴导出
     * @param paramsDTO
     * @return
     */
    @GetMapping("exportTeacherAllowance")
    public Result exportTeacherAllowance(@ModelAttribute TbTeacherAllowanceDTO paramsDTO, HttpServletResponse response) throws IOException {
        Set<Integer> authDeptIds = tbTeacherService.judgeAuth();
        List<TbTeacherAllowanceDTO> res;
        if (authDeptIds != null && authDeptIds.size() == 0) {
            res = new ArrayList<>();
        }else{
            res = tbTeacherService.queryTeacherAllowanceHandle(paramsDTO);
        }
        File file = commService.generateExportFile("导师津贴导出", BusiEnumDefine.TEACHER_ALLOWANCE_EXPORT, (List) res);
        byte[] buffer = new byte[(int) file.length()];
        FileInputStream inputStream = new FileInputStream(file);
        inputStream.read(buffer);
        inputStream.close();

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(Charsets.UTF_8.name());
        String resultFilename = URLEncoder.encode(file.getName(), Charsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + resultFilename);
        response.setHeader("issuccess", "1");
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition,issuccess");
        IoUtil.write(response.getOutputStream(), true, buffer);
        return new Result(true, StatusCodeEnum.NORMAL, res);
    }

    /**
     * 津贴完成申报
     * @param teachSecIds
     * @return
     */
    @PostMapping("finishDeclare")
    public Result finishDeclare(@RequestBody List<Integer> teachSecIds){
        workerService.finishDeclare(teachSecIds);
        return new Result(true, StatusCodeEnum.NORMAL, "成功");
    }

}
